local update_interval = minetest.settings:get("player_rightclick_step") or 0.2
local player_rightclick_range = minetest.settings:get("player_rightclick_range") or 4

p2p = {
  events = {},
  register_on_right_clickplayer = function(func)
    assert(type(func) == "function", "must include a function with the following arguements (clicker, clicked).")
    p2p.events[#p2p.events+1] = func
    return
  end
}

--[Local Function] get clicked player userdata using raycast (returns userdata, if failed returns nil)
--Kudos to jordach for tips relating the use of raycast
local function verify_clicked_player(clicker, range)
  local result = nil

  --Raycast stuff.
  local ray_start = vector.add(clicker:get_pos(), {x=0, y= clicker:get_properties().eye_height, z=0})
  local ray_modif = vector.add(vector.multiply(clicker:get_look_dir(), range), clicker:get_eye_offset())
  local ray_end = vector.add(ray_start, ray_modif)
  local ray = minetest.raycast(ray_start, ray_end, true, false)
  local clicked = ray:next()
  --

  clicked = ray:next()

  if clicked and clicked.type == "object" and clicked.ref:is_player() and clicked.ref ~= clicker then

      result = clicked.ref
  end

  return result
end


local function handle_on_right_clickplayer()

  for _,clicker in pairs(minetest.get_connected_players()) do
    local right_click = clicker:get_player_control().RMB or false

    --Only execute the following if a player is right clicking
    if clicker and right_click == true then
      local name = clicker:get_player_name()
      local clicked = verify_clicked_player(clicker, player_rightclick_range)
      
        --Do right click event when a player was right clicked
        if clicked then
          for _,func in pairs(p2p.events) do 
            func(clicker, clicked)
          end

        end

      break
    end

  end

  minetest.after(update_interval, function()
    handle_on_right_clickplayer()
  end)

end

--Activate player-to-player right clicking handler
minetest.register_on_mods_loaded(function()
  minetest.after(update_interval, function()
    handle_on_right_clickplayer()
  end)
end)